﻿using Application.Job;
using Quartz;

namespace Application.Utils
{
    public static class SchedulerHelper
    {
        public static async Task RebuildJob(this IScheduler scheduler, JobKey jobKey, string cron)
        {
            await scheduler.DeleteJob(jobKey);

            IJobDetail job = JobBuilder.Create<TaskJob>()
            .WithIdentity(jobKey)
            .Build();

            ITrigger trigger = TriggerBuilder.Create()
             .WithIdentity(jobKey.Name, jobKey.Group)
             .StartNow()
             .WithCronSchedule(cron)
             .Build();
            await scheduler.ScheduleJob(job, trigger);
        }

        public static DateTime NextExecutionTime(string cron, DateTime? dateTime = null)
        {
            dateTime = dateTime ?? DateTime.Now;
            var cronE = new CronExpression(cron);
            return cronE.GetNextValidTimeAfter(DateTime.SpecifyKind(Convert.ToDateTime(dateTime), DateTimeKind.Local)).Value.LocalDateTime;
        }
    }
}
